export class EventMgr {
    private static _events: any = {};
    static on(eventname: string, callback: Function, target: any) {
        // if (typeof (eventname) == "string" || typeof (callback) == "function" || typeof (target) == "object") {
        //     console.warn("addListener undefined");
        //     return;
        // }
        if (typeof (EventMgr._events[eventname]) == "undefined") {
            EventMgr._events[eventname] = [];
        }
        EventMgr._events[eventname].push({ callback: callback, target: target });
    }

    static off(eventname: string, callback: Function, target: any) {
        var handlers = EventMgr._events[eventname];
        if (handlers) {
            for (var i = handlers.length - 1; i >= 0; i--) {
                var handler = handlers[i];
                if (target == handler.target && callback.toString() == handler.callback.toString()) {
                    EventMgr._events[eventname].splice(i, 1);
                }
            }
        }
    }

    static offAll(eventname: string) {
        if (typeof (EventMgr._events[eventname]) == "undefined") {
            var handlers = EventMgr._events[eventname];
            for (var i = 0; i < handlers.length; i++) {
                handlers[i] = null;
            }
        }
    }

    static resetAll() {
        for (const key in EventMgr._events) {
            if (EventMgr._events.hasOwnProperty(key)) {
                delete EventMgr._events[key];
            }
        }
    }

    static send(eventname: string, ...arg) {
        if (typeof (EventMgr._events[eventname]) != "undefined") {
            var handlers = EventMgr._events[eventname];
            for (var i = 0; i < handlers.length; i++) {
                var handler = handlers[i];
                handler.callback.apply(handler.target, arg);
            }
        }
    }


    // send(eventname: string, ...arg) {
    //     if (typeof (this._events[eventname]) != "undefined") {
    //         var handlers = this._events[eventname];
    //         for (var i = 0; i < handlers.length; i++) {
    //             var handler = handlers[i];
    //             handler.callback.apply(handler.target,arg);
    //         }
    //     }
    // }
}


